package biolabs.visual.j2d;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;

import biolabs.gui.WindowSink;

public class Java2DWindowSink extends WindowSink<Java2DPainter> {

	private final Canvas canvas;
	private Java2DPainter currentScene = null;

	public Java2DWindowSink() {

		this.canvas = new Canvas() {
			private static final long serialVersionUID = 1L;
			@Override
			public void paint(Graphics g) {
				if(currentScene != null) {
					Graphics2D gfx = (Graphics2D) g;
					AffineTransform savedTr = gfx.getTransform();
					autofit(gfx, currentScene.getBounds(), this.getBounds());
					currentScene.paint(gfx);
					gfx.setTransform(savedTr);
				}
			}
		};
		canvas.setBackground(Color.WHITE);
	}

	public static void autofit(Graphics2D gfx, Rectangle paintingBounds) {
		autofit(gfx, paintingBounds, gfx.getClipBounds());
	}

	public static void autofit(Graphics2D gfx, Rectangle paintingBounds, Rectangle toFrame) {
		double scaleX = toFrame.getWidth() / paintingBounds.getWidth();
		double scaleY = toFrame.getHeight() / paintingBounds.getHeight();
		double trX = toFrame.getX() - paintingBounds.getX();
		double trY = toFrame.getY() - paintingBounds.getY();
		gfx.scale(scaleX, scaleY);
		gfx.translate(trX, trY);
	}

	@Override
	public void push(long time, Java2DPainter data) {
		currentScene = data;
		canvas.repaint();
	}

	@Override
	public void flush() {
		// do nothing
	}

	@Override
	public Component getContent() {
		return canvas;
	}

}
